package org.ethereum.net.dpos;

import java.math.BigInteger;

import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.util.encoders.Hex;

public class EOrgVoteResponse extends EOrgMessage {

	private final long tickets;
	
	private final byte[] electionId;
	
	public EOrgVoteResponse(final byte[] encoded) {
		super(encoded);
		
		RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
		this.tickets = new BigInteger(1, paramsList.get(1).getRLPData()).longValue();
		if (tickets < 1) {
	    		throw new IllegalArgumentException("tickets must be greater then from 1!");
	    }
        this.electionId = paramsList.get(3).getRLPData();
	}
	
	public EOrgVoteResponse(final long tickets, final byte[] electionId, ResponseCode code) {
		super(null);
        this.tickets = tickets;
        if (tickets < 1) {
	    		throw new IllegalArgumentException("tickets must be greater then from 1!");
	    }
        this.electionId = electionId;
        this.responseCode = code;
        encode();
    }
	
	private void encode() {
		byte[] responseCode = RLP.encodeInt(this.responseCode.getCode());
		byte[] round = RLP.encodeBigInteger(BigInteger.valueOf(this.tickets));
		byte[] electionId  = RLP.encodeElement(this.electionId);
		this.encoded = RLP.encodeList(responseCode, round, electionId);
		this.parsed = true;
	}
	
	public long getTickets() {
		return tickets;
	}

	public byte[] getElectionId() {
		return electionId;
	}

	@Override
	public EOrgMessageCodes getCommand() {
		return EOrgMessageCodes.VOTE_RESPONSE;
	}

	@Override
	public byte[] getEncoded() {
		return this.encoded;
	}

	@Override
	public Class<?> getAnswerMessage() {
		return null;
	}

	@Override
	public String toString() {
		return "{round: "+tickets+", electionId: "+Hex.toHexString(electionId)+", responseCode: "+responseCode.toString()+" }";
	}

}
